use std::sync::Arc;

use super::{Class, Method};

// 继承层次中找
pub fn lookup_method_in_class(c: Arc<Class>, name: &str, descriptor: &str) -> Option<Arc<Method>> {
    // 向上查找，自身及所有层级父级的方法中查找
    // let match_name_and_type = |method: &Rc<RefCell<Method>>| method.get_name() == name && method.get_descriptor() == descriptor;
    let mut cc = Some(c.clone());
    while let Some(class) = cc {
        for method in class.get_methods(false) {
            if method.get_name() == name && method.get_descriptor() == descriptor {
                return Some(method);
            }
        }
        cc = class.get_super_class();
    }
    // 查找超接口中是否存在
    for iface in c.get_interfaces() {
        for method in iface.get_methods(false) {
            if method.get_name() == name && method.get_descriptor() == descriptor {
                return Some(method);
            }
        }
    }
    None
}

// 接口中找
pub fn lookup_method_in_interfaces(ifaces: &Vec<Arc<Class>>, name: &str, descriptor: &str) -> Option<Arc<Method>> {
    // let match_name_and_type = |method: &Rc<RefCell<Method>>| method.get_name() == name && method.get_descriptor() == descriptor;
    for iface in ifaces {
        // 再自身方法中查找
        for method in iface.get_methods(false) {
            if method.get_name() == name && method.get_descriptor() == descriptor {
                return Some(method);
            }
        }
        // 上一个层次中找
        if let Some(method) = lookup_method_in_interfaces(iface.get_interfaces(), name, descriptor) {
            return Some(method);
        }
    }
    None
}